package com.onlyyou.pictureserver.controller;

import com.onlyyou.pictureserver.entity.Stock;
import com.onlyyou.pictureserver.info.MsgInfo;
import com.onlyyou.pictureserver.mapper.StockMapper;
import com.onlyyou.pictureserver.service.ImageUrl;
import com.onlyyou.pictureserver.util.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.xml.transform.Result;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @Author: 小野
 * @Date: 2020/1/16 18:58
 */
@RestController
@RequestMapping("/")
public class FileController {
    private static final String TMP_PATH = "e:/projects/tmp";
    @Autowired
    private ImageUrl imageUrl;

    @Autowired
    private StockMapper stockMapper;

    @RequestMapping(value = "/upload", method = RequestMethod.GET)
    public String fileUploadInit() {
        // InfoMsg infoMsg = new InfoMsg();

        return "upload";
    }

    @PostMapping("/upload")
    public Map<String,Object> upload(@RequestParam(value ="file",required = true) MultipartFile file,Long id) {
        Map<String,Object> map=new HashMap<>();
        Stock findStock = stockMapper.findById(id);
        if (null == findStock){
            map.put("msg","未找到商品");
            map.put("code",1);
            map.put("result",false);
            map.put("data",null);
            return map;
        }
        //将图片上传到服务器
        if(file.isEmpty()){
            map.put("msg","项目图片不能为空");
            return map;
        }
        //原始文件名
        String originalFilename = file.getOriginalFilename();
        //文件后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        //图片名称为uuid+图片后缀防止冲突
        String fileName = UUID.randomUUID().toString()+"."+suffix;
        String os = System.getProperty("os.name");
        //文件保存路径
        String filePath="";
        if(os.toLowerCase().startsWith("win")){
            //windows下的路径
            filePath ="D:/ApplictionWork/WorkTools/nginx-1.14.2/images/upload/";
        }else {
            //linux下的路径
            filePath="/root/pictureUpload/project/";
        }
        try {
            //写入图片
            Boolean writePictureflag = FileUtils.uploadFile(file.getBytes(),filePath,fileName);
            if(writePictureflag == false){
                //上传图片失败
                map.put("msg","上传项目图片失败");
                return map;
            }
            //上传成功后，将可以访问的完整路径返回
            String fullImgpath = "/images/upload/"+fileName;
            Stock stock = imageUrl.uploadUrl(id, fullImgpath);
            map.put("msg","上传图片成功");
            map.put("url",fullImgpath);
            map.put("data",stock);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            //上传图片失败
            map.put("msg","上传项目图片失败");
            return map;
        }

    }

    @RequestMapping(value = "/upload1", method = RequestMethod.POST)
    public MsgInfo fileUpload(@RequestParam("uploadFile") MultipartFile file) {
        MsgInfo infoMsg = new MsgInfo();
        if (file.isEmpty()) {
            infoMsg.setCode("error");
            infoMsg.setMsg("Please select a file to upload");
            return infoMsg;
        }

        try {
            File tmp = new File(TMP_PATH, file.getOriginalFilename());
            if(!tmp.getParentFile().exists()){
                tmp.getParentFile().mkdirs();
            }
            file.transferTo(tmp);

            infoMsg.setCode("success");
            infoMsg.setMsg("You successfully uploaded '" + file.getOriginalFilename() + "'");

        } catch (IOException e) {
            infoMsg.setCode("error");
            infoMsg.setMsg("Uploaded file failed");
        }

        return infoMsg;
    }
}
